package me.sort;

import java.util.Arrays;

public class InsertionSort {
    public static void main(String[] args) {
        int[] arr = {6, 4, 3, 5, 1, 2};
        sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        System.out.println("----------------------");
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr) {
        insertion(arr, 1);
    }

    private static void insertion(int[] arr, int low) {
        // 递归出口
        if (low == arr.length) {
            return;
        }
        int temp = arr[low];
        int i = low - 1; // i表示已排序区域指针
        while (i >= 0 && arr[i] > temp) {
            //空出插入位置
            arr[i + 1] = arr[i];
            i--;
        }
        // 找到插入位置
        if (i + 1 != low) {
            arr[i + 1] = temp;
        }

        insertion(arr, low + 1);
    }
}
